package com.zlm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlm.common.CustomException;
import com.zlm.common.Result;
import com.zlm.entity.Category;
import com.zlm.entity.Dish;
import com.zlm.entity.Setmeal;
import com.zlm.mapper.CategoryMapper;
import com.zlm.service.CategoryService;
import com.zlm.service.DishService;
import com.zlm.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    // 菜品的service
    @Autowired
    private DishService dishService;

    // 套餐的service
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id来删除分类,在删除之前要进行判断 看是否有其他菜品在使用这个分类
     *
     * @param id
     * @return
     */
    @Override
    public Result remove(Long id) {
        // 创建查询条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 1.查询当前分类是否关联了其他的菜品，如果已经关联，抛出一个业务异常
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int count = (int) dishService.count(dishLambdaQueryWrapper);

        if (count > 0) {
            // 关联菜品，抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品 不能删除");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 2.查询当前分类是否关联了其他的套餐，如果已经关联，抛出一个业务异常
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int count1 = (int) setmealService.count(setmealLambdaQueryWrapper);

        if (count1 > 0) {
            // 关联菜品，抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐 不能删除");
        }

        // 3.正常删除
        super.removeById(id);

        return Result.success("处理成功");
    }
}
